package cn.hp.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.hp.domain.Role;
import cn.hp.domain.SysUser;
import cn.hp.service.RoleService;
import cn.hp.service.UserService;

@Controller
@RequestMapping("/user")
@Secured({"ROLE_ADMIN"})
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	
	
	//查询所有用户
	@RequestMapping("findAll")
	public ModelAndView findAll(){
		List<SysUser> sysList=userService.findAll();
		ModelAndView andView=new ModelAndView();
		andView.addObject("sysList", sysList);
		andView.setViewName("user-list");
		return andView;
	}
	
	//添加用户
	@RequestMapping("/save")
	public String save(SysUser sysUser){
		userService.save(sysUser);
		return "redirect:findAll";
	}
	
	//判断用户名唯一性
	@RequestMapping("/uniqueName")
	@ResponseBody              //把数据转换为json格式  以流的方式写回页面
	public String uniqueName(String username){
		Boolean b=userService.uniqueName(username);
		return String.valueOf(b);
		
	}
	
	//根据ID查询用户详情
	@RequestMapping("/details")
	public ModelAndView details(Integer id){
		//根据id查询客户信息
		SysUser user=userService.findById(id);
		//根据id查询用户角色和权限,返回值十list是因为能查出来多个角色
		List<Role> roleList=userService.findRolePermission(id);
		
		ModelAndView andView=new ModelAndView();
		andView.addObject("user", user);
		andView.addObject("roleList", roleList);
		andView.setViewName("user-show");
		return andView;
	}
	
	
	//查询所有的角色,  用户已经拥有的角色
	@RequestMapping("/toAddRoleView")
	public ModelAndView toAddRoleView(Integer id){
		//查询所有的角色信息
		List<Role> roleList = roleService.findAll();
		//根据id查询用户已经拥有的角色
		List<Role> userRoleList=userService.findUserRole(id);
		StringBuffer sb=new StringBuffer();
		for (Role role : userRoleList) {
			sb.append(",");
			sb.append(role.getId());
			sb.append(",");
		}
		
		
		ModelAndView andView=new ModelAndView();
		andView.addObject("roleList", roleList);
		andView.addObject("str", sb.toString());
		andView.addObject("userRoleList", userRoleList); 
		andView.addObject("id", id);
		andView.setViewName("user-role-add");
		return andView;
	}
	
	//给用户添加角色
	@RequestMapping("/addRoleToUser")
	public String addRoleToUser(Integer id,Integer [] ids){
		userService.addRoleToUser(id,ids);
		return "redirect:findAll";
		
	}
	
}
